﻿#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void Swap(int* a, int* b)
{
	int c = *a;
	*a = *b;
	*b = c;
}
void InsertSort(int* arr, int n)
{//升序
	for (int i = 0;i < n-1;i++)
	{
		int end = i;//
		int tmp = arr[end + 1];//tmp中存储的是新进来的，待排序的数据
		while (arr[end] > tmp && end >=0)
		{
			arr[end + 1] = arr[end];
			end--;
		}
		arr[end+1] = tmp;
	}
}

void ShellSort(int* arr, int n)
{
	int gap = n;
	while (gap > 1)
	{
		gap = gap / 3 + 1;
		for (int i = 0;i < n - gap;i++)
		{
			int end = i;
			int tmp = arr[end + gap];
			while (arr[end] > tmp && end>=0)
			{
				arr[end + gap] = arr[end];
				end -= gap;
			}
			arr[end + gap] = tmp;
		}
	}
}

//直接选择排序
void SelectSort(int* arr, int n)
{
	int begin = 0;
	int end = n - 1;
	while (begin < end)
	{
		int mini = begin;
		int maxi = begin;
		for (int i = begin;i <= end;i++)
		{	
			if (arr[i] < arr[mini])
			{
				mini = i;
			}
			if (arr[i] > arr[maxi])
			{
				maxi = i;
			}
		}
		if (mini == begin && maxi == end)
		{
			Swap(&arr[begin], &arr[end-1]);
		}
		else
		{
			Swap(&arr[begin], &arr[mini]);
			Swap(&arr[end], &arr[maxi]);//找见最大和最小的分别放在第一个和最后一个位置。
		}
		begin++;
		end--;
	}
}
void BubbleSort(int* a, int n)
{
	int exchange = 0;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n - i - 1; j++)
		{
			if (a[j] > a[j + 1])
			{
				exchange = 1;
				Swap(&a[j], &a[j + 1]);
			}
		}
		if (exchange == 0)
		{
			break;
		}
	}
}

int _QuickSort(int* a, int left, int right)
{
	int keyi = left;
	left++;
	while (left <= right)
	{
		//right:从右往左找比基准值小的
		while (left <= right && a[right] > a[keyi])
		{
			right--;
		}
		//left:从左往右找比基准值大的
		while (left <= right && a[left] < a[keyi])
		{
			left++;
		}
		if (left <= right)
		{
			Swap(&a[left++], &a[right--]);
		}
	}
	Swap(&a[keyi], &a[right]);//与小于基准值的交换
	return right;
}
void QuickSort(int* a, int left, int right)
{
	if (left >= right) {
		return;
	}
	//_QuickSort用于按照基准值将区间[left,right)中的元素进⾏划分 
	int meet = _QuickSort(a, left, right);
	QuickSort(a, left, meet - 1);
	QuickSort(a, meet + 1, right);
}

int main()
{
	int a[10] = { 5,3,9,6,2,4,7,1,8 };
	QuickSort(a,0,8);
	for (int i = 0;i < 9;i++)
	{
		printf("%d ",a[i]);
	}
	return 0;
}